import Prism from 'prismjs';
import 'prismjs/components/prism-javascript.min.js';
import 'prismjs/components/prism-java.min.js';

import * as React from 'react';

export function CodeBlock({ children, language }) {

  const ref = React.useRef(null);

  React.useEffect(() => {
    if (ref.current) {
      // 清除之前的高亮效果
      const preElement = ref.current;
      while (preElement.firstChild) {
        preElement.removeChild(preElement.firstChild);
      }

      // 确保 code 是字符串类型，如果是数组，合并为字符串
      const codeString = Array.isArray(children)
        ? children.join('\n')
        : children;

      // 高亮代码
      let highlightedCode = Prism.highlight(
        codeString,
        Prism.languages[language],
        language
      );

      // 将高亮后的 HTML 分割成行
      const lines = highlightedCode.split('\n').filter(Boolean);

      // 将每行代码包装在 <div> 中
      const formattedCode = lines.map((line, index) => (
        <div key={index} dangerouslySetInnerHTML={{ __html: line }} />
      ));

      // 渲染高亮后的代码
      preElement.innerHTML = '';
      preElement.appendChild(
        document.createElement('div')
      ).innerHTML = `<div>${formattedCode
        .map((line) => line.props.dangerouslySetInnerHTML.__html)
        .join('</div><div>')}</div>`;
    }
  }, [children, language]);

  return (
    <div className="code" aria-live="polite">
      <pre ref={ref} className={`language-${language}`}>
      </pre>
      <style jsx>
        {`
          .code {
            position: relative;
          }

          /* Override Prism styles */
          .code :global(pre[class*='language-']) {
            text-shadow: none;
          }
          .space {
            display: inline-block;
            width: 0.5em; /* 调整空格的宽度 */
          }
        `}
      </style>
    </div>
  );
}
